<template>
  <div class="chat">
    <div class="chat-main">
      <div class="chat-tips" :class="tipsShow?'':'chat-put-tips'">
        <span @click="tipsShow=true">
          您好，兔世界平台人工客服工作时间： 工作日9:00-18:00，现在是非工作时间，请您在会话中留言，待工作时间，将会安排人工客服为您优选处理，带来不便，敬请谅解。
          服务时间：工作日：09:00:00-18:00:00
        </span>
        <a v-if="tipsShow" @click="tipsShow=false">收起</a>
      </div>
      <ul class="message-list" ref="messageEle" id="messageEle">
        <p class="message-more" v-if="!isCompleted">
          查看更多</p>
        <li v-for="(item,index) in messages" :key="index">
          <MessageBubble :data="item">
            <MessageText :data="item"></MessageText>
            <template #dialog>
              <ul class="dialog-item">
                <li @click="handleMseeage('copy')">
                  <i class="icon icon-msg-copy"></i>
                  <span>复制</span>
                </li>
                <li @click="handleMseeage('forward')">
                  <i class="icon icon-msg-forward"></i>
                  <span>转发</span>
                </li>
                <li @click="handleMseeage('reply')">
                  <i class="icon icon-msg-quote"></i>
                  <span>引用</span>
                </li>
                <li @click="handleMseeage('revoke')">
                  <i class="icon icon-msg-revoke"></i>
                  <span>撤回</span>
                </li>
                <li @click="handleMseeage('delete')">
                  <i class="icon icon-msg-del"></i>
                  <span>删除</span>
                </li>
              </ul>
            </template>
          </MessageBubble>
        </li>
      </ul>
    </div>
    <div class="chat-footer">
      <div class="func" id="func">
        <main class="func-main">
          <component v-for="(item,index) in pluginComponentList" :key="index" :is="item" @send="handleSend"
            parentID="func" />
        </main>
      </div>
      <div class="input">
        <textarea ref="inputEle" v-model="text" placeholder="请输入您要咨询的问题～" data-type="text" rows="1" @input="inputChange"
          @keyup.enter="sendMseeage" @keyup.delete="deleteAt" @blur="inputBlur = true" @focus="inputBlur = false"
          @keypress="geeks"></textarea>
        <button class="input-btn" data-type="text" :disabled="!text" @click="sendMseeage">
          <p class="input-btn-hover">按Enter发送，Ctrl+Enter换行</p>
          发送
        </button>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { nextTick, reactive, ref, watch } from 'vue'
import MessageBubble from './components/message-bubble.vue';
import MessageText from './components/message-text.vue';
import Face from './plugin-components/face/Face.vue';
import Accessory from './plugin-components/accessory/Accessory.vue';
import Flower from './plugin-components/Flower/flower.vue';
import constant from '../constant';

const inputEle = ref<any>()
const messageEle = ref<any>()
const text = ref('')
const messageList = reactive([])
const tipsShow = ref(false)
const isCompleted = ref(false)
const inputComposition = ref(false)
const inputCompositionCont = ref('')
const toBottomTipCont = ref('')
const inputBlur = ref(false)
const needToBottom = ref(false)
const isFirstRender = ref(true)
const isUserAction = ref(false)
const needGroupReceipt = ref(false)
const atType = reactive([])
let atOneText: never[] = []
const scroll = reactive({
  scrollTop: 0,
  scrollHeight: 0,
  scrollTopMin: Infinity,
  scrollTopMax: 0,
})
const conversation = {} as Conversation

interface IMessage {
  ID?: string;
  name?: String;
  msg?: String;
  flow: String;
  src?: String;
  avatar?: String;
  conversationType?: String;
  nameCard?: String;
  nick?: String;
  from?: String;
  status?: String;
  isPeerRead?: Boolean;
  readReceiptInfo?: {
    unreadCount: number,
    readCount: number
  };
  cloudCustomData?: String;
  payload?: any
}

interface Conversation {
  conversationID?: string;
  type?: string;
  subType?: string;
  unreadCount?: number;
  lastMessage?: {
    nick?: string;
    nameCard?: string;
    lastTime?: number;
    lastSequence?: number;
    fromAccount?: string;
    isPeerRead?: boolean;
    messageForShow?: string;
    type?: string;
    payload?: {
      [propName: string]: any;
    };
  };
  groupProfile?: {
    [propName: string]: any;
  };
  userProfile?: {
    [propName: string]: any;
  };
  groupAtInfoList?: Array<{ [propName: string]: any }>;
  remark?: string;
  isPinned?: boolean;
  messageRemindType?: string;
}

const messages = reactive<IMessage[]>([
  { name: "text", msg: "熬夜有什么用，又没人陪你聊天，早点休息吧。", flow: 'in' },
  { name: "img", msg: "", src: "https://web.sdk.qcloud.com/component/TUIKit/assets/avatar_21.png", flow: 'out' },
  { name: "text", msg: "经济上的", flow: 'in' },
  { name: "text", msg: "o品牌方", flow: 'out' },
  { name: "text", msg: "去哦皮肤", flow: 'in' },
  { name: "text", msg: "开发能看出", flow: 'out' }
])

const pluginComponentList: any = [Accessory, Face, Flower];

watch(messages, (newVal: Array<any>, oldVal: Array<any>) => {
  nextTick(() => {
    const isTheSameMessage = newVal[newVal.length - 1]?.ID === oldVal[oldVal.length - 1]?.ID;
    if (newVal.length === 0 || isTheSameMessage) {
      return;
    }
    handleScroll();
  })
})

watch(
  () => scroll.scrollTop,
  (newVal: number) => {
    setTimeout(() => {
      // scrolling end
      if (newVal === messageEle?.value?.scrollTop) {
        if (scroll.scrollTopMin !== Infinity && scroll.scrollTopMax !== 0) {
          // sendMessageReadInView('scroll');
        }
        scroll.scrollTopMin = Infinity;
        scroll.scrollTopMax = 0;
      }
    }, 20);
  },
  { deep: true },
);

const handleSend = (emo: any) => {
  text.value += emo.name;
  inputEle.value.focus();
};

const inputChange = (e: any) => {
  if (inputComposition) {
    inputCompositionCont.value = e?.data ? e.data : '';
  }
}

const sendMseeage = async (event: Event) => {
  console.log(event);
}


/**
 * 未
 */
const deleteAt = () => {
  const array = atOneText;
  for (let index = 0; index < array.length; index++) {
    // 判断输入框中是否有@+尼克/名片/用户名字符串。
    // Judge whether there is a string of @ + Nick / namecard / userid in the input box.
    const flagName = `${constant.at}${(array[index] as any).name}`;
    if (text.value.indexOf(flagName) === -1) {
      const { userID } = array[index]
      atType.splice(atType.indexOf(userID), 1)
      atOneText = [];
    }
  }
  return atType;
}

const geeks = (e: any) => {
  if (e.keyCode === 13) {
    e.preventDefault();
    if (e.ctrlKey) {
      e.target.value += '\n';
      text.value += '\n';
    }
  }
};

/**
 * 右键/长按
 */
const handleMseeage = async (type: string) => {
  switch (type) {
    case 'revoke':

      break;
    case 'copy':

      break;
    case 'delete':

      break;
    case 'forward':

      break;
    case 'reply':

  }
};

const handleScroll = () => {
  if (isFirstRender) {
    needToBottom.value = false;
    scrollToTarget('bottom');
    isFirstRender.value = false;
    return;
  }
  if (messageEle.value) {
    const { scrollHeight, scrollTop, clientHeight } = messageEle.value;
    if (
      scrollHeight - (scrollTop + clientHeight) <= clientHeight
      || messages[messages.length - 1]?.flow === 'out'
    ) {
      scrollToTarget('bottom');
    } else {
      handleToBottomTip(true);
    }
  }
};

const scrollToTarget = (type: string, targetElement?: HTMLElement) => {
  messageEle.value.removeEventListener('scroll', onScrolling);
  isUserAction.value = true;
  switch (type) {
    case constant.scrollType.toBottom:
      needToBottom.value = false;
      messageEle?.value?.lastElementChild.scrollIntoView(false);
      // getImgLoad(messageEle?.value, 'message-img', async () => {
      //   messageEle?.value?.lastElementChild?.scrollIntoView(false);
      //   messageEle.value.addEventListener('scroll', onScrolling);
      //   await sendMessageReadInView('page');
      // });
      break;
    case constant.scrollType.toTarget:
      targetElement?.scrollIntoView(false);
      // getImgLoad(messageEle?.value, 'message-img', async () => {
      //   targetElement?.scrollIntoView(false);
      //   messageEle.value.addEventListener('scroll', onScrolling);
      //   await sendMessageReadInView('page');
      // });
      break;
    default:
      break;
  }
};

const handleToBottomTip = (needToBottom: boolean) => {
  switch (needToBottom) {
    case true:
      needToBottom = true;
      if (conversation?.unreadCount && conversation?.unreadCount > 0) {
        toBottomTipCont.value = `${conversation?.unreadCount} '条新消息'`;
      } else {
        toBottomTipCont.value = '回到最新位置';
      }
      break;
    case false:
      needToBottom = false;
      break;
    default:
      needToBottom = false;
      break;
  }
};

const onScrolling = () => {
  const { scrollHeight, scrollTop, clientHeight } = messageEle.value;
  if (needGroupReceipt.value) {
    scroll.scrollHeight = scrollHeight;
    scroll.scrollTop = scrollTop;
    scroll.scrollTopMin = isUserAction
      ? scroll.scrollTopMin
      : Math.min(scroll.scrollTopMin, scroll.scrollTop);
    scroll.scrollTopMax = isUserAction
      ? scroll.scrollTopMax
      : Math.max(scroll.scrollTopMax, scroll.scrollTop);
  }
  if (scrollHeight - (scrollTop + clientHeight) > clientHeight) {
    handleToBottomTip(true);
  } else {
    handleToBottomTip(false);
  }
  isUserAction.value = false;
};

const sendMessageReadInView = () => { }
</script>

<style scoped lang="scss">
@import './style/index.scss';
</style>